import cv2  # 利用opencv读取图像
import numpy as np
import os
import time
import sys

def videoToText(VPath, interval):
    SAVE_PATH = ".\\picture_out\\"
    cap = cv2.VideoCapture(VPath)
    i = 0
    j = 0
    index = 0
    frames = []
    while True:
        success, frame = cap.read()
        i += 1
        if not success:
            print('video is all read')
            break

        if i % interval == 0:
            # 保存图片
            j += 1
            save_name = str(j) + '_' + str(i) + '.jpg'
            # cv2.imwrite(SAVE_PATH + save_name, frame)
            # print('image of %s is saved' % save_name)

            # 生成文本化的图片
            ImgToTxt(SAVE_PATH + save_name,185)
            # frames.append()
            index = index + 1
            print("进度：%d/6574" % index)
'''
    strfra = str(frames).replace("'","").replace("0x","").replace("[","").replace("]","\n")

    fo = open("HexData.txt", 'a')
    fo.write(strfra)
    fo.close()
'''


def ImgToTxt(img, interval):
    RAGE = 64
    txtName = img.split("\\")[-1].split(".")[0] # 取图片名称
    savePath = ".\\txtout\\"
    img = cv2.imread(img)  # 读取图像
    # 获得图像大小
    height, width = img.shape[:2]
    size = (RAGE, RAGE)
    img = cv2.resize(img, size, interpolation=cv2.INTER_AREA) # 改变图片大小比例
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 将图片转换为灰度图
    ret, img_gray = cv2.threshold(img_gray, interval, 255, cv2.THRESH_BINARY) # 二值化处理
    high = len(img_gray)
    weith = len(img_gray[0])
    BinPct = np.zeros((high, weith), dtype = int) # 生成文本矩阵
    HexList = []
    for i in range(int(high)):
        x = "0"*RAGE
        for j in range(int(weith)):
            if img_gray[i][j] == 255:
                BinPct[i][j] = 1
                x = x[:j] + "1" + x[j + 1:]
        # print(str(hex(int(x[:32],2))))
        f0 = open(".\\HexData\\HexData_"+str(i)+"_0.hex",'a')
        f1 = open(".\\HexData\\HexData_"+str(i)+"_1.hex",'a')
        f0.write(str(hex(int(x[:32],2))).replace("0x","") + "\n")
        f1.write(str(hex(int(x[32:],2))).replace("0x","") + "\n")
        f0.close()
        f1.close()
'''
        HexList.append(hex(int(x[:32],2))) # 生成16进制数据
        HexList.append(hex(int(x[32:],2)))
        # print(x)
        # HexList[i] = HexList[i].replace("0x","")
        # print(HexList)
    # np.savetxt(savePath + txtName + ".txt",BinPct,fmt='%d') # 输出文本矩阵
    return HexList
'''

if __name__ == '__main__':
        videoToText("BadApple.mp4",1)